<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>店铺管理</title>
  <!--引入的vue.js-->
  <script src="../../js/vue.js"></script>
  <!--引入elementUI的css-->
  <link type="text/css" rel="stylesheet" href="../../css/index.css">
  <!--引入elementUI的js-->
  <script src="../../js/index.js"></script>
  <!--引入axios.js-->
  <script src="../../js/axios.min.js"></script>

  <style>
    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 30px;
    }
    .image-slot i {
      font-size: 20px;
    }
  </style>

</head>
<body>
<!-- Vue应用根元素 -->
<div id="app" class="app1">
  <!-- 搜索区域 - 使用Element UI栅格系统布局 -->
  <el-row>
    <!-- 店铺ID搜索框 -->
    <el-col :span="6">
      <el-input size="mini"
                v-model="searchForm.shopId"
                placeholder="请输入店铺ID"
                size="small">
      </el-input>
    </el-col>

    <!-- 店铺名称搜索框 -->
    <el-col :span="6">
      <el-input size="mini"
                v-model="searchForm.shopName"
                placeholder="请输入店铺名称"
                size="small">
      </el-input>
    </el-col>

    <!-- 联系电话搜索框 -->
    <el-col :span="6">
      <el-input size="mini"
                v-model="searchForm.contactPhone"
                placeholder="请输入联系电话"
                size="small">
      </el-input>
    </el-col>

    <!-- 搜索按钮 -->
    <el-col :span="6">
      <el-button size="mini"
                 type="primary"
                 icon="el-icon-search"
                 @click="search"
                 size="small">
        搜索
      </el-button>

    </el-col>
  </el-row>

  <!-- 店铺数据表格 -->
  <el-table :data="tableData" style="width: 100%">
    <!-- 店铺ID列 -->
    <el-table-column prop="shopId" label="店铺ID" width="80"></el-table-column>
    <!-- 店铺名称列 -->
    <el-table-column prop="shopName" label="店铺名称" width="120"></el-table-column>

    <!-- 联系电话列 -->
    <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>

    <!-- 店铺地址列 -->
    <el-table-column prop="shopAddress" label="店铺地址" width="150"></el-table-column>

    <!-- 经营类型列 -->
    <el-table-column prop="businessType" label="经营类型" width="120"></el-table-column>

    <!-- 状态列 -->
    <el-table-column prop="status" label="状态" width="80">
      <template slot-scope="scope">
        <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
          {{ scope.row.status === '0' ? '正常' : '停用' }}
        </el-tag>
      </template>
    </el-table-column>

    <!-- 审核状态列 -->
    <el-table-column prop="auditStatus" label="审核状态" width="100">
      <template slot-scope="scope">
        <el-tag v-if="scope.row.auditStatus === '0'" type="info">待审核</el-tag>
        <el-tag v-else-if="scope.row.auditStatus === '1'" type="success">通过</el-tag>
        <el-tag v-else type="danger">拒绝</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="createBy" label="创建者" width="100"></el-table-column>
    <!-- 创建时间列 -->
    <el-table-column prop="createTime" label="创建时间" width="180">
      <template slot-scope="scope">
        {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ').substring(0, 19) : '' }}
      </template>
    </el-table-column>

    <!-- 营业执照列 -->
    <el-table-column label="营业执照" width="120">
      <template slot-scope="scope">
        <div v-if="scope.row.businessLicence">
          <el-image
                  :src="scope.row.businessLicence"
                  :preview-src-list="[scope.row.businessLicence]"          style="width: 80px; height: 80px;"
                  fit="cover"
                  lazy>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
        <div v-else>
          <span>无</span>
        </div>
      </template>
    </el-table-column>

    <!-- 操作列 -->
    <el-table-column label="操作" fixed="right" width="200">
      <template slot-scope="scope">
        <!-- 编辑按钮 -->
        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>

        <!-- 删除按钮 -->
        <el-button size="mini"
                   type="danger"
                   @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[3,5,10,15,20,100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
  </el-pagination>

  <!-- 更新店铺对话框 -->
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px">
    <!-- 表单 -->
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <!-- 店铺名称输入框 -->
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="form.shopName" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 店铺LOGO输入框 -->
      <el-form-item label="店铺LOGO" prop="shopLogo">
        <el-input v-model="form.shopLogo" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 联系电话输入框 -->
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 店铺地址输入框 -->
      <el-form-item label="店铺地址" prop="shopAddress">
        <el-input v-model="form.shopAddress" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 经营类型输入框 -->
      <el-form-item label="经营类型" prop="businessType">
        <el-input v-model="form.businessType" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 截单时间输入框 -->
      <el-form-item label="截单时间" prop="cutOffTime">
        <el-input v-model="form.cutOffTime" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 结算周期输入框 -->
      <el-form-item label="结算周期(天)" prop="settlementCycle">
        <el-input v-model="form.settlementCycle" autocomplete="off"></el-input>
      </el-form-item>

      <!-- 状态选择框 -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 备注输入框 -->
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="form.remark" autocomplete="off" :rows="3"></el-input>
      </el-form-item>
      <!-- 在备注输入框后添加以下内容 -->
      <el-form-item label="营业执照" prop="businessLicence">
        <el-upload
                class="upload-demo"
                action="/vegetablemarketexpress/shop/uploadBusinessLicenceImage"
                name="pic"
                :on-success="handleBusinessLicenceSuccess"
                :on-error="handleBusinessLicenceError"
                :before-upload="beforeBusinessLicenceUpload"
                :limit="1"
                :file-list="businessLicenceFileList"
                list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-upload>
        <el-input v-model="form.businessLicence" type="hidden"></el-input>
        <div v-if="form.businessLicence">
          <img :src="form.businessLicence" style="width: 100px; height: 100px; margin-top: 10px;" />
        </div>
      </el-form-item>




    </el-form>

    <!-- 对话框底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        tableData: [],              // 表格数据
        currentPage: 1,             // 当前页码
        pageSize: 5,                // 每页显示条数
        total: 0,                   // 总条数
        searchForm: {               // 搜索条件
          shopId: '',
          shopName: '',
          contactPhone: '',
        },
        title: '更新店铺',           // 对话框标题
        dialogFormVisible: false,   // 店铺表单对话框是否可见
        form: {                     // 店铺表单数据
          shopId: '',
          purchaserId: '',
          shopName: '',
          shopLogo: '',
          contactPhone: '',
          shopAddress: '',
          businessType: '',
          cutOffTime: '',
          settlementCycle: '',
          status: '0',
          remark: '',
          businessLicence: ''       // 添加营业执照字段
        },

        // 表单验证规则
        rules: {
          shopName: [
            { required: true, message: '请输入店铺名称', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
          ],
          shopAddress: [
            { required: true, message: '请输入店铺地址', trigger: 'blur' }
          ]
        },
        businessLicenceFileList: []// 营业执照文件列表
      }
    },
    created() {
      // 页面加载时加载数据
      this.loadData();
    },
    methods: {
      // 加载店铺数据
      loadData() {
        let _this = this;
        // 发送POST请求获取分页数据
        axios.post('/vegetablemarketexpress/shop/selectShopListAuditStatus', {
          "pageNo": this.currentPage,
          "pageSize": this.pageSize,
          "data": this.searchForm
        }).then(function (response) {
          if (response.data.code == 200) {
            _this.tableData = response.data.data.list;
            _this.total = response.data.data.total;
            /*// 为每个店铺获取商家名称
            _this.tableData.forEach(shop => {
              _this.loadMerchantName(shop);
            });*/
          }
        }).catch(function (error) {
          console.log(error);
          _this.$message.error('数据加载失败');
        });
      },
/*      // 加载商家名称
      loadMerchantName(shop) {
        // 如果后端没有返回商家名称，根据create_by字段查询
        if (!shop.createByNickName && shop.createBy) {
          axios.post('/vegetablemarketexpress/user/getUserNickNameById', {
            userId: shop.createBy
          }).then(response => {
            if (response.data.code == 200) {
              // 使用Vue.set确保响应式更新
              this.$set(shop, 'createByNickName', response.data.data);
            } else {
              this.$set(shop, 'createByNickName', '未知商家');
            }
          }).catch(error => {
            console.error('获取商家名称失败:', error);
            this.$set(shop, 'createByNickName', '获取失败');
          });
        }
      },*/
      // 每页条数改变时触发
      handleSizeChange(val) {
        this.pageSize = val;
        this.currentPage = 1;
        this.loadData();
      },

      // 当前页改变时触发
      handleCurrentChange(val) {
        this.currentPage = val;
        this.loadData();
      },

      // 搜索功能
      search() {
        this.currentPage = 1;
        this.loadData();
      },

      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let uri = '/vegetablemarketexpress/shop/insertShop';
            if (this.title == '店铺更新') {
              uri = '/vegetablemarketexpress/shop/updateShop';
            }

            let _this = this;
            let submitForm = JSON.parse(JSON.stringify(this.form));

            axios.post(uri, submitForm)
                    .then(function (response) {
                      if (response.data.code == 200) {
                        _this.$message({
                          message: '操作成功',
                          type: 'success'
                        });
                        _this.loadData();
                        _this.dialogFormVisible = false;
                      } else {
                        _this.$message.error('操作失败: ' + response.data.msg);
                      }
                    })
                    .catch(function (error) {
                      console.log(error);
                      _this.$message.error('操作异常');
                    });
          } else {
            this.$message.error('表单验证失败');
          }
        });
      },

      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },



      // 处理编辑店铺
      handleEdit(index, row) {
        this.dialogFormVisible = true;
        this.title = "店铺更新";
        // 深拷贝避免直接引用
        this.form = JSON.parse(JSON.stringify(row));
        // 回显营业执照
        this.businessLicenceFileList = [];
        if (this.form.businessLicence) {
          const fileName = this.form.businessLicence.substring(this.form.businessLicence.lastIndexOf('/') + 1);
          this.businessLicenceFileList.push({
            name: fileName,
            url: this.form.businessLicence
          });
        }
      },



      // 处理删除店铺
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该店铺, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _this = this;
          // 发送删除请求
          axios.delete('/vegetablemarketexpress/shop/deleteShopById?shopId=' + row.shopId)
                  .then(function (response) {
                    if (response.data.code == 200) {
                      _this.$message({
                        message: '删除成功',
                        type: 'success'
                      });
                      _this.loadData();
                    } else {
                      _this.$message.error('删除失败: ' + response.data.msg);
                    }
                  })
                  .catch(function (error) {
                    console.log(error);
                    _this.$message.error('删除异常');
                  });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 营业执照上传前处理
      beforeBusinessLicenceUpload(file) {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPGOrPNG) {
          this.$message.error('上传营业执照只能是 JPG 或 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传营业执照大小不能超过 2MB!');
        }
        return isJPGOrPNG && isLt2M;
      },
      // 营业执照上传成功处理
      handleBusinessLicenceSuccess(response, file, fileList) {
        /*if (response.code === 200) {
          // 从正确的路径获取URL
          const url = response.data && response.data.url ? response.data.url : response.url;
          if (url) {
            this.form.businessLicence = url;
            this.$message.success('营业执照上传成功');
          } else {
            this.$message.error('营业执照上传返回URL异常');
          }
        } else {
          this.$message.error('营业执照上传失败: ' + (response.msg || '未知错误'));
        }*/
        if (response.code === 200) {
          // 后端返回 {filePath: "图片地址", originName: "原文件名"}
          this.form.businessLicence = response.data.filePath;
          this.$message.success('营业执照上传成功');
        } else {
          this.$message.error('营业执照上传失败: ' + (response.msg || '未知错误'));
        }
      },
      // 营业执照上传错误处理
      handleBusinessLicenceError(err, file, fileList) {
        this.$message.error('营业执照上传失败: ' + (err.message || '未知错误'));
        console.error('Upload error:', err);
      },
    }
  });
</script>


</body>
</html>
